package com.matchmealpha;

import java.util.Scanner;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class AlertView extends LinearLayout implements OnClickListener {

	private TextView userLink;
	private TextView maintext;
	private TextView picLink;
	private Button acceptButton;
	private Button denyButton;
	private int callerID;
	private Context context;
	private Alert alert;
	private String sessionid;
	private RelativeLayout loadingPanel;

	private static final int F_APPROVE = 1;
	private static final int F_DENY = 2;
	private static final int M_APPROVE = 3;
	private static final int M_DENY = 4;
	private static final String F_URL_APPROVE = MatchMeTabWidget.MM_SERVER
			+ "/accept_friend";
	private static final String F_URL_DENY = MatchMeTabWidget.MM_SERVER
			+ "/deny_friend";
	private static final String M_URL_DENY = MatchMeTabWidget.MM_SERVER
			+ "/deny_matchme";
	private static final String M_URL_APPROVE = MatchMeTabWidget.MM_SERVER
			+ "/accept_matchme";

	public AlertView(Context context, Alert alert, int callerID,
			String sessionid) {
		super(context);
		/* inflating layout */
		this.context = context;
		this.callerID = callerID;
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		inflater.inflate(R.layout.alert_item_view, this, true);

		this.userLink = (TextView) this.findViewById(R.id.AlertItemUserLinkText);
		this.picLink = (TextView) this.findViewById(R.id.AlertItemPicLinkText);
		this.maintext = (TextView) this.findViewById(R.id.AlertItemMainText);
		this.acceptButton = (Button) this.findViewById(R.id.AlertItemAcceptButton);
		this.denyButton = (Button) this.findViewById(R.id.AlertItemDenyButton);
		
		this.alert = alert;
		this.sessionid = sessionid;
		loadingPanel = (RelativeLayout) findViewById(R.id.AlertViewLoadingPanel);
		loadingPanel.setVisibility(View.GONE);

		switch (alert.getType()) {
		case ('C'):
			this.acceptButton.setVisibility(View.GONE);
			this.denyButton.setVisibility(View.GONE);
			this.maintext.setText(" comments on your ");
			break;
		case ('M'):
			this.picLink.setVisibility(View.GONE);
			this.maintext.setText(" wants to MatchMe");
			break;
		case ('F'):
			this.picLink.setVisibility(View.GONE);
			this.maintext.setText(" wants to be your friend");
			break;
		}

		setAlertItem(alert);
		initListener();
	}

	public void setAlertItem(Alert alert) {
		this.userLink.setText(alert.getUserID2());
		this.picLink.setText("photo");
	}

	private void initListener() {
		this.userLink.setOnClickListener(this);
		this.picLink.setOnClickListener(this);
		this.acceptButton.setOnClickListener(this);
		this.denyButton.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case (R.id.AlertItemUserLinkText):
			Intent intent1 = new Intent(this.context, TimelineActivity.class);
			intent1.putExtra("back", true);
			intent1.putExtra("callerID", this.callerID);
			intent1.putExtra("curruser", this.userLink.getText());
			intent1.putExtra("relationship", false);
			View view1 = MatchMeTabWidget.getCurrGroup(this.callerID)
					.getLocalActivityManager().startActivity(
							"TimelineActivity",
							intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
					.getDecorView();
			MatchMeTabWidget.myReplaceView(view1, this.callerID);
			break;
		case (R.id.AlertItemPicLinkText):
			Intent intent2 = new Intent(this.context, PostActivity.class);
			intent2.putExtra("callerID", this.callerID);
			View view2 = MatchMeTabWidget.getCurrGroup(this.callerID)
					.getLocalActivityManager().startActivity("PostActivity",
							intent2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
					.getDecorView();
			MatchMeTabWidget.myReplaceView(view2, this.callerID);
			break;
		case (R.id.AlertItemAcceptButton):
			// TODO update DB and refresh the view or call cameraview
			switch (alert.getType()) {
			case ('C'):
				Log.d("AlertView", "Shouldn't be here");
				break;
			case ('M'):
				//rework
				// loadingPanel.setVisibility(View.VISIBLE);
				Intent in = new Intent(context, ShareActivity.class);
				in.putExtra("postid", alert.getTypeID());
				in.putExtra("alertid", alert.getAlertID());
				in.putExtra("requester", alert.getUserID2());
				context.startActivity(in);
				maintext.setText(maintext.getText() + "Accepted");
				acceptButton.setEnabled(false);
				denyButton.setEnabled(false);
				MatchMeTabWidget.alertList.remove(alert);
				//new AlertTask().execute(M_APPROVE, alert.getAlertID());
				break;
			case ('F'):
				loadingPanel.setVisibility(View.VISIBLE);
				new AlertTask().execute(F_APPROVE, alert.getAlertID());
				break;
			}

			break;
		case (R.id.AlertItemDenyButton):
			// TODO update DB and refresh the view
			switch (alert.getType()) {
			case ('C'):
				Log.d("AlertView", "Shouldn't be here");
				break;
			case ('M'):
				//	
				loadingPanel.setVisibility(View.VISIBLE);
				new AlertTask().execute(M_DENY, alert.getAlertID());
				break;
			case ('F'):
				loadingPanel.setVisibility(View.VISIBLE);
				new AlertTask().execute(F_DENY, alert.getTypeID(), alert
						.getAlertID());
				break;
			}
			break;
		}
	}

	private class AlertTask extends AsyncTask<Integer, Void, Boolean> {
		private String updatedText = "";

		protected Boolean doInBackground(Integer... data) {

			HttpRequest req = new HttpRequest(sessionid);
			String response = "";

			switch (data[0]) {
			case F_APPROVE:
				response = req.sendPost(F_URL_APPROVE + "/" + data[1], "");
				updatedText = "...Accepted";
				break;
			case F_DENY:
				response = req.sendPost(F_URL_DENY + "/" + data[1], "");
				updatedText = "...Denied";
				break;
			case M_APPROVE:
				//response = req.sendPost(M_URL_APPROVE, "");
				updatedText = "...Accepted";
				Post p = new Post();
				if (getPostObject(p) /*&& getPicArray(p)*/) {
					MatchMeTabWidget.recentList.add(p);
					MatchMeTabWidget.timelineList.add(p);
					return true;
				} else {
					return false;
				}
			case M_DENY:
				response = req.sendPost(M_URL_DENY + "/" + data[1], "");
				updatedText = "...Denied";
				break;
			}

			if (MatchMeTabWidget.REQUEST_SUCCESS.equals(response)) {
				switch (data[0]) {
				case F_APPROVE:
					MatchMeTabWidget.friendsList.add(alert.getUserID2());
					return true;
				case M_APPROVE:
					//TODO Shouldn't be here
				case M_DENY:
				case F_DENY:
					return true;
				default:
					return false;
				}
			} else {
				return false;
			}
		}

		protected void onPostExecute(Boolean result) {
			loadingPanel.setVisibility(View.GONE);
			if (result) {
				maintext.setText(maintext.getText() + updatedText);
				acceptButton.setEnabled(false);
				denyButton.setEnabled(false);
				MatchMeTabWidget.alertList.remove(alert);
			}
		}

//		private boolean getPicArray(Post post) {
//			HttpRequest req = new HttpRequest(sessionid);
//			String response2 = "";
//
//			byte[] byteArr = req.getByteArray(MatchMeTabWidget.MM_SERVER
//					+ "/get_image/" + post.getPostID());
//			int[] otherImage = MatchMeTabWidget.byteToIntArray(byteArr);
//			int[] finalImage = FilterEffects.combineImages(otherImage, post
//					.getPicID());
//
//			if (!MatchMeTabWidget.USER_AUTH_FAILURE.equals(response2)
//					&& !MatchMeTabWidget.REQUEST_FAILURE.equals(response2)) {
//				post.setPicID(finalImage);
//				return true;
//			}
//			return false;
//		}

		private boolean getPostObject(Post post) {
			HttpRequest req2 = new HttpRequest(sessionid);
			String response2 = "";
			response2 = req2.sendPost(MatchMeTabWidget.MM_SERVER + "/get_post/"
					+ alert.getTypeID(), "");

			if (!MatchMeTabWidget.USER_AUTH_FAILURE.equals(response2)
					&& !MatchMeTabWidget.REQUEST_FAILURE.equals(response2)) {
				Scanner in = new Scanner(response2);
				if (in.hasNext()) {
					post.setPostID(in.nextInt());
					post.setUserID1(in.next());
					post.setUserID2(in.next());
					// post.setPicID(in.nextInt());
					post.setLocation1(in.next());
					post.setLocation2(in.next());
					post.setStatus(in.next());
					post.setTime1(in.next());
					post.setTime2(in.next());
					post.setDescription1(in.next());
					post.setDescription2(in.next());
					return true;
				}
			}
			Log.d("ALERTVIEW","FAIL TO DOWNLOAD POST OBJECT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
			return false;
		}
	}
}
